using System;
using System.IO;
using System.Runtime.Serialization;

namespace FuzzyTaskList
{
    public class FileSystemDataProvider<T> : TaskDataProviderBase<T> where T : new()
    {

        private string _path;
        public FileSystemDataProvider(String path)
        {
            _path = Path.Combine(path, TaskDataProviderBase<T>.AppFolderName);
            Directory.CreateDirectory(_path);
        }

        public override void Save(T data)
        {
            string fullPath = Path.Combine(_path, FileSystemDataProvider<T>.DataFileName);
            var ser = new DataContractSerializer(data.GetType());
            using (var stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                ser.WriteObject(stream, data);
            }
        }

        public override T Load()
        {
            string fullPath = Path.Combine(_path, FileSystemDataProvider<T>.DataFileName);
            if (File.Exists(fullPath))
            {
                var ser = new DataContractSerializer(typeof(T));
                using (var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    T pc = (T)ser.ReadObject(stream);
                    return pc;
                }
            }
            return new T();
        }

    }
}
